<?php

namespace App\Models;


use App\Service\Ip;
use Illuminate\Support\Facades\DB;

class NewsComment extends Base
{

    // 用户新鲜事：收藏
    protected $table = 'news_comment';
    const UPDATED_AT = null;

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid', 'news_id',];

    // 评论
    // 评论, $pid = 0
    public function onComment($uid, $news_id, $content, $pid = 0, $terminal = '')
    {
        if(empty($uid)){
            return $this->return_false("请指定评论的用户!");
        }
        if(empty($news_id)){
            return $this->return_false("请指定评论的内容编号!");
        }

        $userDb  = new User();
        $modifDb = new UserModify();
        $model   = new News();

        $where = ["id" => $news_id,];
        $info  = $model->isCache(true)->oneFind($where);
        if(empty($info)){
            return $this->return_false("内容不存在!");
        }
        if(isset($info['is_draft']) && $info['is_draft'] == 1){
            return $this->return_false("你要点赞的内容未通过审核!");
        }
        if($info['verify'] == 0){
            return $this->return_false("你要点赞的内容未通过审核!");
        }
        if($info['verify'] == -1){
            return $this->return_false("你要点赞的内容已经删除!");
        }
        // 新鲜事才会投诉
        if(!empty($info['is_complain']) && ($info['is_complain'] == 1)){
            return $this->return_false("你要点赞的内容已经被投诉!");
        }

        // 是否已经评估操作过了
        $behaviorDb = new ArticleBehavior();
        $where4     = ["uid" => $uid, "behavior" => "comment", "news_id" => $news_id, 'status' => 1,];
        $isBehavior = $behaviorDb->where($where4)->first();

        $ip = request()->ip();
        // 保存评论
        $behavior = $where4;
        $cacheNum = ["comment_no" => "+1"];
        $addon    = ["comment_no" => DB::raw("comment_no+1")];
        $comment  = ['uid' => $uid, "news_id" => $news_id, 'content' => $content, 'ip_address' => $ip, 'ip' => (new Ip())->getIpAddress($ip), 'pid' => $pid, 'terminal' => $terminal, 'verify' => 1]; // 'pid' => $pid,
        $this->fill($comment);
        //$upComment = ["reply_no" => DB::raw("reply_no+1")];

        // 用户发布数量
        $userData = ["publish_no" => DB::raw('publish_no+1'), 'mtime' => LARAVEL_TIME];

        // 执行操作
        DB::beginTransaction();
        try{
            // 保存评论
            $result = $this->save();

            // 更新父级
            /*if($pid){
                $this->where("id", $pid)->update($upComment);
            }*/

            // 评论数量
            $model->where('id', $news_id)->update($addon);
            $modifDb->where('uid', $uid)->update($addon);

            // 评论操作记录  如果不存在则添加
            if(empty($isBehavior)){
                $behaviorDb->fill($behavior)->save();
            }

            // 如果是评论 则增加用户发布数量用于热门用户搜索
            $userDb->where('id', $uid)->update($userData);

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheShow($comment);
        $model->deleteCacheShow(['id' => $news_id]); // 文章或者新闻的缓存（列表数量也要编号）
        $userDb->deleteCacheShow(['id' => $uid]);
        if(empty($isBehavior)){
            $behaviorDb->deleteCacheShow($behavior);
        }

        return $this->id;
    }

    // 删除
    public function softDelete($where, $ids)
    {
        $lists = $this->where($where)->whereIn('id', $ids)->get()->toArray();
        if(empty($lists)){
            return $this->return_false('你要删除的数据不存在！！');
        }

        // 查找有关的用户，快讯，长短文，文章，需求，活动
        $_ids    = array_column($lists, 'id');
        $userNum = $newsNum = [];
        foreach($lists as $item){
            $_uid = $item['uid'];

            $_aid = $item['news_id'];
            // 重新整理
            $userNum[$_uid] = ($userNum[$_uid] ?? 0) + 1;
            $newsNum[$_aid] = ($newsNum[$_aid] ?? 0) + 1;

        }

        $userDb = new User();
        $newsDb = new News();
        DB::beginTransaction();
        try{
            // 删除文章附件，属性，日志，评论
            $this->whereIn('id', $_ids)->update(['verify' => -1]);

            // 减少文章评论数量
            if($newsNum){
                foreach($newsNum as $kk => $nn){
                    $newsDb->where('id', $kk)->update(['comment_no' => DB::raw("comment_no-".$nn)]);
                }
            }

            // 减少用户文章数量
            if($userNum){
                foreach($userNum as $kk => $nn){
                    $userData = ['publish_no' => DB::raw("publish_no-".$nn),];
                    $userDb->where('id', $kk)->update($userData);
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // 缓存操作
        $this->deleteCacheList($lists);
        $this->deleteCacheShow(['id' => $_ids, 'verify' => -1]);
        if($userNum){
            foreach($userNum as $kk => $nn){
                $userDb->reSaveCache($kk, ['publish_no' => "-".$nn,]);
            }
        }
        if($newsNum){
            foreach($newsNum as $kk => $nn){
                $newsDb->reSaveCache($kk, ['comment_no' => "-".$nn]);
            }
        }

        return true;
    }

    // 定义验证操作
    public function rules()
    {

        $add = [
        ];

        $edit = [
        ];

        $info = [
        ];


        $rule = [
            'uid'     => 'required',
            'content' => 'required',
            'news_id' => 'numeric',
            //'status'  => ['in:0,1,2'],
        ];


        $msg = [
            'id'      => '自编号',
            'news_id' => '新鲜事id',
            'uid'     => '用户id',
            'content' => '评论内容',
            'ctime'   => '创建时间',
            'mtime'   => '创建时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add];
    }
}
